layui.define(['layer', 'upload'], function (exports) {
    let upload = layui.upload;
    let do_upload = {
        singular: function (fun, opt) {
            let base = {
                accept: 'image',
                acceptMime: 'image/*',
                exts: 'jpg|png|gif|bmp|jpeg',
                size: 1024 * 20
            }
            $.extend(base, opt)
            return upload_file(fun, base);
        },
        more: function (fun, opt) {
            let base = {
                multiple: true
            }
            $.extend(base, opt)
            return upload_file(fun, base);
        },
        file: function (fun, opt) {
            let base = {
                accept: 'file'
            }
            $.extend(base, opt)
            return upload_file(fun, base);
        }
    }

    //去掉因上传gif图导致返回地址携带的后缀
    function delete_suffix(data) {
        return data.split("?")[0];
    }

    //文件上传
    function upload_file(fun, opt) {
        let config = {
            elem: '#' + opt.id,
            done: function (res) {
                //如果上传失败
                if (res.code > 0) {
                    return layer.msg('上传失败');
                }
                if (res.res.requestUrls[0].indexOf("?") >= 0) {
                    res.res.requestUrls[0] = delete_suffix(res.res.requestUrls[0])
                }
                //上传成功
                if (fun && typeof fun == 'function') {
                    fun(res)
                }
            }
        }
        for (let key in opt) {
            if (key != id) {
                config[key] = opt[key]
            }
        }
        upload.render(config);
    }

    exports('common_upload', do_upload);
});


function delete_img(data, dom) {
    $(dom).parent().remove();
}


